package org.mathig.poker.player;

import java.io.IOException;
import java.util.Arrays;

import org.mathig.poker.Action;
import org.mathig.poker.AfterBetActions;
import org.mathig.poker.AfterNothingActions;
import org.mathig.poker.Card;
import org.mathig.poker.Context;
import org.mathig.poker.Player;

public class HumanPlayer implements Player {

	private String name;

	private Card[] cards;

	public HumanPlayer(String name) {
		this.name = name;
	}

	public void receive(Context context, Card[] cards) {
		this.cards = cards;
	}

	public boolean doYouMuck(Context table) {
		return true;
	}

	public String getName() {
		if (name == null) {
			System.out.println("Your name ? ");
			name = read();
		}
		return name;
	}

	public static String read() {
		StringBuffer buffer = new StringBuffer();
		try {
			boolean b = true;
			while (b) {
				int n = System.in.read();
				if (n == -1) {
					b = false;
				} else {
					char c = (char) n;
					switch (c) {
					case '\n':
						break;
					case '\r':
						b = false;
						break;
					default:
						buffer.append(c);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	private void printContext(Context context) {
		System.out.println(getName() + " > cards = " + Arrays.toString(cards) + ", board = " + context.getBoard());
		System.out.println(getName() + " > pot = " + context.getPot() + ", stack = " + context.getStack(this));
		System.out.println(getName() + " > highest bet = " + context.getBet() + ", actual bet = " + context.getBet(this));
	}

	public Action response(Context context, AfterNothingActions actions) {
		printContext(context);
		System.out.println(getName() + " > Action : -1.Fold 0.Check N.Bet ?");
		int action = Integer.parseInt(read());
		switch (action) {
		case 0:
			return actions.fold();
		case 1:
			return actions.check();
		default:
			return actions.bet(action);
		}
	}

	public Action response(Context context, AfterBetActions actions) {
		printContext(context);
		System.out.println(getName() + " > Action : -1.Fold 0.Call N.Raise ?");
		int action = Integer.parseInt(read());
		switch (action) {
		case 0:
			return actions.fold();
		case 1:
			return actions.call();
		default:
			return actions.raise(action);
		}
	}

}
